package com.itheima.boottlias.aop;

import cn.hutool.core.util.ArrayUtil;
import com.itheima.boottlias.domain.dto.LoginDTO;
import com.itheima.boottlias.domain.pojo.EmpLoginLog;
import com.itheima.boottlias.domain.vo.LoginVO;
import com.itheima.boottlias.domain.vo.Result;
import com.itheima.boottlias.ex.CustomException;
import com.itheima.boottlias.mapper.EmpLoginLogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author ghy
 * @version 1.0
 * @since 2025-07-20 08:36
 */
@Aspect
@Component
public class LoginLogAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Around("execution(* com.itheima.boottlias.controller.LoginController.login(..))")
    public Object recordLoginLog(ProceedingJoinPoint pjp) {
        EmpLoginLog empLoginLog = new EmpLoginLog();
        Object[] args = pjp.getArgs();
        if(ArrayUtil.isNotEmpty(args)) {
            //System.out.println(args[0]);
            LoginDTO loginDTO = (LoginDTO) args[0];
            empLoginLog.setUsername(loginDTO.getUsername());
            empLoginLog.setPassword(loginDTO.getPassword());
        }
        long start = System.currentTimeMillis();
        try {
            Result result = (Result) pjp.proceed();
            long end = System.currentTimeMillis();
            empLoginLog.setLoginTime(LocalDateTime.now());
            empLoginLog.setIsSuccess(result.getCode().shortValue());
            empLoginLog.setJwt(empLoginLog.getIsSuccess() == 1 ?
                    ((LoginVO)result.getData()).getToken() : null);
            empLoginLog.setCostTime(end-start);
            return result;
        } catch (Throwable e) {
            long end = System.currentTimeMillis();
            empLoginLog.setLoginTime(LocalDateTime.now());
            empLoginLog.setIsSuccess((short) 0);
            empLoginLog.setCostTime(end-start);
            throw new CustomException(e.getMessage());
        } finally {
            empLoginLogMapper.insert(empLoginLog);
        }
    }



}
